<template>
  <div class="container">
    <el-dialog
      :title="title"
      :visible="showSubjectDialog"
      width="30%"
      @close="closeSubjectDialog"
    >
      <!-- >Form表单 -->
      <el-form ref="subjectRef" :model="addSubjectForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="addSubjectForm.subjectName" placeholder="请输入学科名称" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="addSubjectForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSubjectDialog">取 消</el-button>
        <el-button type="primary" @click="clickAddSubject">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectAdd',
  props: {
    showSubjectDialog: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      required: true
    }
  },

  data() {
    return {
      addSubjectForm: {
        id: null,
        subjectName: '',
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: ['change', 'blur'] }],
        isFrontDisplay: [{ required: true, type: 'number', message: '请选择是否显示', tirgger: ['change', 'blur'] }]
      },
      title: ''

    }
  },

  methods: {
    open() {
      if (this.editData.id) {
        const { id, subjectName, isFrontDisplay } = this.editData
        this.addSubjectForm = { id, subjectName, isFrontDisplay }
      } else {
        this.addSubjectForm = {
          id: null,
          subjectName: '',
          isFrontDisplay: 1
        }
      }
    },
    // 关闭对话框
    closeSubjectDialog() {
      this.$emit('update:showSubjectDialog', false)
      this.addSubjectForm = {
        id: null,
        subjectName: '',
        isFrontDisplay: 1
      }
      this.$refs.subjectRef.resetFields()
    },
    // 点击对话框确定按钮
    clickAddSubject() {
      this.$refs.subjectRef.validate(async(valid) => {
        if (valid) {
          if (this.addSubjectForm.id) {
            // 修改学科
            this.addSubjectForm.id = this.editData.id
            await update(this.addSubjectForm)
            // 1.提示信息
            this.$message.success('修改学科成功')
          } else {
            // 新增学科
            await add(this.addSubjectForm)
            // 1.提示信息
            this.$message.success('新增学科成功')
          }
          // 2.关闭弹框
          this.closeSubjectDialog()
          // 3.重置列表
          this.$emit('reload')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
